package com.hww.gannan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hww.gannan.common.UserExport;
import com.hww.gannan.dao.FriendlyLinkDao;
import com.hww.gannan.dao.MessageDao;
import com.hww.gannan.dao.SysLoginDao;
import com.hww.gannan.entity.FriendlyLink;
import com.hww.gannan.entity.Message;
import com.hww.gannan.entity.SysLogin;
import com.hww.gannan.service.AdminService;
import com.hww.gannan.util.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.beans.Visibility;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private MessageDao messageDao;
    @Resource
    private SysLoginDao sysLoginDao;
    @Resource
    private FriendlyLinkDao friendlyLinkDao;
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 100, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(512));

    @Override
    public Result getMessageList(Integer pageNum, Integer pageSize) {
        Page<Message> page = new Page<>(pageNum, pageSize);
        Page<Message> messagePage = messageDao.selectPage(page, null);
        return Result.success(messagePage);
    }

    @Override
    public Result getSysLoginList(Integer pageNum, Integer pageSize) {
        Page<SysLogin> page = new Page<>(pageNum, pageSize);
        Page<SysLogin> messagePage = sysLoginDao.selectPage(page, null);
        return Result.success(messagePage);
    }

    @Override
    public Result getUrlList(Integer pageNum, Integer pageSize) {
        Page<FriendlyLink> page = new Page<>(pageNum, pageSize);
        Page<FriendlyLink> messagePage = friendlyLinkDao.selectPage(page, null);
        return Result.success(messagePage);

    }

    @Override
    public Result addFriendlyLink(FriendlyLink friendlyLink) {
        friendlyLinkDao.insert(friendlyLink);
        return Result.success(null);
    }

    @Override
    public Result delFriendlyLink(Integer id) {
        friendlyLinkDao.deleteById(id);
        return Result.success(null);
    }

    @Override
    public void export(HttpServletResponse response) {
        try {

            int pageNum = 1;
            int pageSize = 10000;
            UserExport userExport = new UserExport();
            String[] head = new String[]{"1", "2", "3"};

            ExcelWriter excelWriter = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX);
            Long num = messageDao.selectCount(null);

            ArrayList<CompletableFuture> futureArrayList = new ArrayList<>();
            if (num > 10000) {
                CompletableFuture[] cfArray = new CompletableFuture[(int) (num / 10000)];
                // long l = num / 10000;
                BigDecimal bigDecimalNum = new BigDecimal(num);
                BigDecimal divide = bigDecimalNum.divide(new BigDecimal(10000), 0, BigDecimal.ROUND_UP);
                int l = divide.intValue();
                for (int i = 1; i <= l; i++) {
                     int finalI = i;
                    CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
                                int page = (finalI - 1) * pageSize;
                                List<Message> arrayList = messageDao.selectAllPage(page, pageSize);
                                if (arrayList.size() > 0) {
                                    userExport.addAll(arrayList, head, excelWriter, finalI + "", finalI);
                                }
                            }, executor);
                    futureArrayList.add(completableFuture);
                 /*   executor.execute(() -> {
                        int page = (finalI - 1) * pageSize;
                        List<Message> arrayList = messageDao.selectAllPage(page, pageSize);
                        if (arrayList.size() > 0) {
                            userExport.addAll(arrayList, head, excelWriter, finalI + "", finalI);
                        }
                        System.out.println("执行第" + finalI + "条");
                    });*/
                }

                CompletableFuture<Void> completableFuture = CompletableFuture.allOf(futureArrayList.toArray(cfArray));// 全执行完
                System.out.println("开始堵塞执行");
                completableFuture.join();//
                System.out.println("堵塞执行完毕");
/* executor.shutdown();
                while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    System.out.println();
                }*/
            }

            //  userExport.multipleExport("wode",response);
            System.out.println("执行完毕");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("牛博666.xlsx", "UTF-8"));
            excelWriter.finish();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
